//
//  QMAShareDelegateImp.m
//  QQMiniGameSDKDemo
//
//  Created by Goyoungs on 2023/4/14.
//

#import "QMAShareDelegateImp.h"
#import "WXApi.h"
#import "WXApiObject.h"
#import "AppDelegate.h"
#import "SDWebImageManager.h"
#import "ImageCompressTool.h"
#import <TencentOpenAPI/QQApiInterface.h>

NSString *const DemoShareQQCompleteNotification = @"DemoShareQQCompleteNotification";

#define DEMO_SHARE_ERROR_CODE -1

@interface QMAShareDelegateImp()
@property(nonatomic, copy) void (^shareQQCompleteBlock)(NSError *_Nullable error) ;
@end

@implementation QMAShareDelegateImp

- (instancetype)init {
    if(self = [super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shareToQQResult:) name:DemoShareQQCompleteNotification object:nil];   //监听QQ分享结果
    }
    return self;
}

- (void)shareToQQResult:(NSNotification *)notification {
    NSString *result = [notification object];
    if(![result isKindOfClass:[NSString class]]) {
        return;
    }
    BOOL success = [result isEqualToString:@"0"];
    if(self.shareQQCompleteBlock) {
        self.shareQQCompleteBlock(success ? nil : [NSError errorWithDomain:@"QMAShareErrorDomain" code:DEMO_SHARE_ERROR_CODE userInfo:nil]);
        self.shareQQCompleteBlock = nil;
    }
}

/// 分享的接口
/// @param shareModel 分享model
/// @param application application实例
/// @param scene 场景
/// @param completionBlock 回调
- (void)shareMessageWithModel:(QMAShareModel *_Nonnull)shareModel
                  application:(MABaseApplication *_Nonnull)application
                        scene:(MAShareScene)scene
              completionBlock:(nullable void (^)(NSError *_Nullable error))completionBlock {
    //TODO: 宿主实现分享逻辑
    NSString *jumpUrl = @"";                              //跳转url
    if(shareModel.dataToShare.length > 0) {
        NSData *jsonData = [shareModel.dataToShare dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                             options:NSJSONReadingMutableContainers
                                                               error:&err];
        jumpUrl = dict[@"jump_url"];
    }
    NSString *previewImageUrl = shareModel.imageUrl;        //图片地址
    NSLog(@"分享图片地址 %@",previewImageUrl);
    NSString *title = application.appInfo.appName;          //标题
    NSString *description = shareModel.title;               //描述
    
    MAShareTarget type = shareModel.config.shareTarget;
    switch (type) {
        case MAShareTargetQQ:
        case MAShareTargetQQFastForward:
        case MAShareTargetChatFastShare:
        case MAShareTargetFastShareTable:
        case MAShareTargetOpenIdShare:
        case MAShareTargetQzone: {
            QQApiNewsObject *newsObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:jumpUrl]
                                                                title:title
                                                          description:description
                                                      previewImageURL:[NSURL URLWithString:previewImageUrl]];
            [self sendMessageToQQWithObjects:newsObj type:type complete:completionBlock];
        }
            break;
        case MAShareTargetWXFriends:
        case MAShareTargetWXMoment: {
            
            WXWebpageObject *ext = [WXWebpageObject object];
            ext.webpageUrl = jumpUrl;
            
            WXMediaMessage *message = [WXMediaMessage message];
            message.title = title;
            message.description = description;
            message.mediaTagName = @"WECHAT_TAG_JUMP_SHOWRANK";
            message.mediaObject = ext;
            [self sendMessageToWXWithObjects:message type:type imageUrl:previewImageUrl complete:completionBlock];
        }
            break;
        default:
            break;
    }
}

- (void)sendMessageToQQWithObjects:(QQApiNewsObject *)newsObject
                              type:(MAShareTarget)type
                          complete:(void (^)(NSError *error))complete {
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:newsObject];
    QQApiSendResultCode code = EQQAPISENDSUCESS;
    if(type == MAShareTargetQzone) {
        code = [QQApiInterface SendReqToQZone:req];
    }
    else {
        code = [QQApiInterface sendReq:req];
    }
    if(code != EQQAPISENDSUCESS) {
        if(complete) {
            complete([NSError errorWithDomain:@"QMAShareErrorDomain" code:-1 userInfo:nil]);
        }
        self.shareQQCompleteBlock = nil;
    }
    else {
        //等待QQ分享结果回调
        self.shareQQCompleteBlock = complete;
    }
}

- (void)sendMessageToWXWithObjects:(WXMediaMessage *)messageObjects
                              type:(MAShareTarget)type
                          imageUrl:(NSString *)imageUrl
                          complete:(void (^)(NSError *error))complete {
    
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    __weak typeof(self) weakSelf = self;
    [manager loadImageWithURL:[NSURL URLWithString:imageUrl?:@""]
                        options:0
                       progress:nil
                    completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            if(!weakSelf) {
                return;
            }
            if(image) {
                NSInteger maxByte = 32 * 1024;  //微信要求不超过32K
                NSData *realData = [ImageCompressTool compressImageSize:image toByte:maxByte times:3];
                if(realData.length < maxByte) {
                    messageObjects.thumbData = realData;
                }
                else {
                    NSLog(@"图片压缩结果超过32k");
                }
            }
            
            SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
            req.message = messageObjects;
            req.bText = NO;
            req.scene = type == MAShareTargetWXFriends ? WXSceneSession : WXSceneTimeline;
//            [WXApi sendReq:req completion:^(BOOL success) {
//                if(complete) {
//                    //wx调起分享即成功
//                    complete(success == YES ? nil : [NSError errorWithDomain:@"QMAShareErrorDomain" code:DEMO_SHARE_ERROR_CODE userInfo:nil]);
//                }
//            }];
//            [WXApi sendReq:req];
            [WXApi sendReq:req completion:nil];
        });
    }];
}

/// 分享在没有传imageURL情况下，获取默认的分享imageURL
/// @param appInfo 小游戏appinfo
/// @param shareTarget  分享类型
- (NSString *_Nonnull)defaultImageURL:(MAAppInfo *_Nonnull)appInfo shareTarget:(MAShareTarget)shareTarget {
    return appInfo.iconURL;
}

+ (BOOL)handleOpenURL:(NSURL *)url {
    NSString *scheme = url.scheme;
    NSLog(@"handleOpenURL scheme %@",scheme);
    //TODO: 宿主替换scheme
    if(![scheme isEqualToString:@"qqminigamedemo"]) {
        return NO;
    }
    NSString *host = url.host;
    NSLog(@"handleOpenURL host %@",host);
    //TODO: 宿主替换host
    if(![host isEqualToString:@"minisdk"] ) {
        return NO;
    }

    NSURLComponents *urlComponents = [[NSURLComponents alloc] initWithString:url.absoluteString];
    NSMutableDictionary *query = [NSMutableDictionary dictionary];
    [urlComponents.queryItems enumerateObjectsUsingBlock:^(NSURLQueryItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [query setValue:obj.value forKey:obj.name];
    }];
    NSString *link = query[@"link"];
    NSInteger scene = [query[@"scene"] integerValue];
    if(link.length == 0) {
        return NO;
    }
    
    AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UIViewController *rootVC = appdelegate.window.rootViewController;
    if(!rootVC) {
        return NO;
    }
    [[QQMiniAppSDKManager sharedInstance] showApplicationWithLink:link scene:(MAEntryScene)scene parentVC:rootVC hostModel:nil];

    return YES;
}

@end
